package com.quanshu.exchange.ui.gui.message.friends;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.GroupMemberEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 群发消息 - 选择好友 - 我的好友
 * Created by xiniu003 on 2017/12/12.
 */

public class SelectFriendActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.commit_btn)
    LinearLayout commitBtn;

    private List<UserEntity> userEntityList;
    private SingleAdapter<UserEntity> adapter;
    private List<String> beSelectedList;
    private List<GroupMemberEntity> groupMemberEntities;
    private boolean enable;
    private List<String> newSelectedList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_friend);
        ButterKnife.bind(this);
        initIntent();
        initView();
        initData();
        initListener();
    }

    private void initIntent() {
        beSelectedList = (List<String>) getIntent().getSerializableExtra("List<String>");
        groupMemberEntities = (List<GroupMemberEntity>) getIntent().getSerializableExtra("List<GroupMemberEntity>");
    }

    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleAdapter<>(new DataDisplayer<UserEntity>(this, R.layout.item_select_friend_layout) {
            @Override
            public void bindData(BaseViewHolder holder, LayoutWrapper<UserEntity> wrapper, UserEntity item, int position) {
                holder.setRoundImageUrl(R.id.friend_avatar, item.getAvatar(), R.drawable.default_avatar);
                holder.setText(R.id.friend_name, AppUtils.getUserName(item));
                String letter = AppUtils.getUserInitialLetter(item);
                // 处理分割线
                int nextPosition = position + 1;
                if (nextPosition < userEntityList.size()) {
                    UserEntity nextUser = userEntityList.get(position + 1);
                    String nextHead = AppUtils.getInitialLetter(AppUtils.getUserName(nextUser));
                    if (letter.equals(nextHead)) {
                        holder.setVisibility(R.id.item_contacts_bottom_divider, View.VISIBLE);
                    } else {
                        holder.setVisibility(R.id.item_contacts_bottom_divider, View.GONE);
                    }
                }
                if (position == userEntityList.size() - 1) {
                    holder.setVisibility(R.id.item_contacts_last_bottom_divider, View.VISIBLE);
                } else {
                    holder.setVisibility(R.id.item_contacts_last_bottom_divider, View.GONE);
                }
                // 处理head字母
                if (position == 0) {
                    holder.setVisibility(R.id.friend_sort_letter, View.VISIBLE);
                    holder.setText(R.id.friend_sort_letter, letter);
                } else {
                    int lastPosition = position - 1;
                    if (lastPosition < 0) {
                        lastPosition = 0;
                    }
                    UserEntity lastUser = userEntityList.get(lastPosition);
                    if (letter.equals(AppUtils.getUserInitialLetter(lastUser))) {
                        holder.setVisibility(R.id.friend_sort_letter, View.GONE);
                    } else {
                        holder.setVisibility(R.id.friend_sort_letter, View.VISIBLE);
                        holder.setText(R.id.friend_sort_letter, letter);
                    }
                }
                ImageView checkBox = holder.getView(R.id.friend_check);
                if (groupMemberEntities != null && groupMemberEntities.size() > 0) {
                    for (GroupMemberEntity groupMemberEntity : groupMemberEntities) {
                        if (groupMemberEntity.getMemberid().equals(item.getMemberid())) {
                            checkBox.setSelected(true);
                            checkBox.setEnabled(false);
                            return;
                        }
                    }
                }
                if (beSelectedList != null && beSelectedList.contains(item.getMemberid())) {
                    if (!enable) {
                        checkBox.setEnabled(false);
                    }
                    checkBox.setSelected(true);
                } else {
                    checkBox.setSelected(false);
                    checkBox.setEnabled(true);
                }
                checkBox.setOnClickListener(view -> {
                    boolean status = checkBox.isSelected();
                    if (!status) {
                        newSelectedList.add(item.getMemberid());
                    } else {
                        Iterator<String> it = newSelectedList.iterator();
                        while (it.hasNext()) {
                            if (it.next().equals(item.getMemberid())) {
                                it.remove();
                                break;
                            }
                        }
                    }
                    checkBox.setSelected(!status);
                });
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void initData() {

        if (beSelectedList != null) {
            newSelectedList.addAll(beSelectedList);
        }
        userEntityList = UserDao.getInstance().queryForAll();
        if (userEntityList != null) {
            AppUtils.sortDataByPinYin(userEntityList);
            adapter.setData(userEntityList);
        }
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().clicks(commitBtn, aVoid -> doCommit());
    }

    private void doCommit() {

        if (newSelectedList == null || newSelectedList.size() < 1) {
            ToastHelper.toast("请选择成员");
            return;
        }
        Intent intent = getIntent();
        intent.putExtra("List<String>", (Serializable) newSelectedList);
        setResult(RESULT_OK, intent);
        finish();
    }

}
